package cm.stu.util;

import cm.stu.pojo.Person;
import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.*;

public class ConnectionFactory {
	//获取数据源 自动读取c3p0-config.xml文件
	private static DataSource dataSource = new ComboPooledDataSource();

	//获取连接
	public static Connection getConnection() {
		try {
			return dataSource.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	//资源关闭工具方法
	public static void close(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet) {
		try {
			//释放资源，根据先开后放
			if(resultSet != null)  resultSet.close();
			if(preparedStatement != null)  preparedStatement.close();
			if(connection != null)  connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

    public static Person Login(Person p, DatabaseMetaData connectionFactory) {
        String sql = "select * from person where useAccount='"+p.getUserAccount()+"' and userPassword='"+p.getUserPassword()+"'";
        Connection connection = ConnectionFactory.getConnection();
        PreparedStatement pre = null;
        ResultSet res = null;
        Person newPerson = null;
        try{
            pre = connection.prepareStatement(sql);
            res = pre.executeQuery();
            while (res.next()){
                newPerson = new Person();
                //封装账户密码所对应的信息
                // //'userAccount' 'userName' 'userSex' 'userBirthday' 'userIdCard' 'userPassword' 'userIdentify''userOtherName'
                newPerson.setUserAccount(res.getString("userAccount"));
                newPerson.setUserName(res.getString("userName"));
                newPerson.setUserSex(res.getString("userSex"));
                newPerson.setUserBirthday(res.getString("userBirthday"));
                newPerson.setUserIdCard(res.getString("userIdCard"));
                newPerson.setUserPassword(res.getString("userPassword"));
                newPerson.setUserIdentify(res.getInt("userIdentify"));
                newPerson.setUserOtherName(res.getString("userOtherName"));

            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


        return newPerson;
    }
}
